package com.dyz.leetcode._05_sort;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;

public class _56_merge {
    public int[][] merge(int[][] intervals) {
        Arrays.sort(intervals, new Comparator<int[]>() {
            @Override
            public int compare(int[] o1, int[] o2) {
                return o1[0]-o2[0];
            }
        });

        ArrayList<int[]> outputs = new ArrayList<>();
        for(int i=0; i<intervals.length; i++){
            int[] currInterval = intervals[i];
            if(outputs.isEmpty()){
                outputs.add(currInterval);
            }else {//判断是否有重叠，有的话则合并
                int[] outputsLastInterval = outputs.get(outputs.size()-1);
                int outputLastRight = outputsLastInterval[1];
                int currLeft = currInterval[0];
                if(outputLastRight< currLeft){
                    outputs.add(currInterval);
                }else {
                    int currRight = currInterval[1];
                    outputsLastInterval[1] = Math.max(outputLastRight, currRight);
                }
            }
        }
        return outputs.toArray(new int[outputs.size()][]);
    }

}
